﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

using ERPStore.Extensions;

using Microsoft.Practices.Unity;

namespace ERPStore.Cart
{
	public class PluginInit : ERPStore.Extensibility.PluginInit
	{
		public PluginInit()
		{
			Container = GlobalConfiguration.Configuration.DependencyResolver.GetContainer();			
		}

		Microsoft.Practices.Unity.IUnityContainer Container { get; set; }

		public override void AddServices()
		{
			var settings = new Models.Settings();
			settings.BindFromConfiguration(ERPStore.Cart.Configuration.ConfigurationSettings.AppSettings);

			Container.RegisterInstance<Models.Settings>(settings, new ContainerControlledLifetimeManager());

			if (settings.RepositoryName == "mock")
			{
				// For tests
				Container.RegisterType<Repositories.ICartRepository, Repositories.MockCartRepository>(new ContainerControlledLifetimeManager());
			}
			else
			{
				Container.RegisterType<CloudSoft.Repositories.IRepositoryInitializer, CloudSoft.Repositories.Initializers.SqlSchemaInitializer<Repositories.CartDbContext>>("cartschemainitializer", new PerResolveLifetimeManager());
				Container.RegisterType<CloudSoft.Repositories.IDbContextFactory<Repositories.CartDbContext>, Repositories.DbContextFactory>(new PerThreadLifetimeManager());
				Container.RegisterType<Repositories.CartDbContext>(new PerThreadLifetimeManager());
				Container.RegisterType<Repositories.ICartRepository, Repositories.SqlCartRepository>(new Microsoft.Practices.Unity.ContainerControlledLifetimeManager());
			}

			// Services
			Container.RegisterType<ERPStore.Services.ICartService, Services.CartService>(new ContainerControlledLifetimeManager());
			Container.RegisterType<Services.AdminCartService>(new ContainerControlledLifetimeManager());

			// Validator
			Container.RegisterType<global::FluentValidation.IValidator<ERPStore.Models.OrderCart>, ModelValidators.CartValidator>("Validator:" + typeof(ERPStore.Models.OrderCart).FullName, new ContainerControlledLifetimeManager());

		}

		public override void Load()
		{
			var settings = Container.Resolve<Models.Settings>();
			if (settings.RepositoryName == "sql")
			{
				var initializer = Container.Resolve<CloudSoft.Repositories.IRepositoryInitializer>("cartschemainitializer");
				initializer.Initialize("_erpstore_cart_schema");
			}

			var leadSourceRegistrationService = Container.Resolve<ERPStore.Services.ILeadSourceRegistrationService>();
			leadSourceRegistrationService.RegisterLeadSource(new Cart.Models.AssignSource());
		}


	}
}
